package org.mrzc.mvc.listener;

import javax.servlet.ServletContext;

/**
 * 仅存储系统路径
 */
public final class ServerPath
{
    /**
     * 获取应用服务路径 获取结果例如：D:/jboss-eap-4.3/jboss-as/server/default/./deploy/ui.war'
     */
    private String realPath = "";
    /**
     * 获取应用服务WEB-INF路径
     * 获取结果例如：D:/jboss-eap-4.3/jboss-as/server/default/./deploy/ui.war/WEB-INF
     */
    private String webPath = "";
    /**
     * 获取应用服务classes路径
     * 获取结果例如：D:/jboss-eap-4.3/jboss-as/server/default/./deploy/ui.war/WEB-INF/classes
     */
    private String classPath = "";

    public static ServerPath mLisServerPath = null;

    private ServerPath()
    {
    }

    public static ServerPath getInstance()
    {
        if (mLisServerPath == null)
        {
            mLisServerPath = new ServerPath();
        }
        return mLisServerPath;
    }

    protected void loadServerPath(ServletContext cServletContext)
    {
        if ("".equals(realPath))
        {
            realPath = cServletContext.getRealPath("").replace("\\", "/");
        }
        if ("".equals(webPath))
        {
            webPath = realPath + "/WEB-INF";
        }
        if ("".equals(classPath))
        {
            classPath = realPath + "/WEB-INF/classes";
        }
    }

    public String getRealPath()
    {
        return realPath;
    }

    public String getWebPath()
    {
        return webPath;
    }

    public String getClassPath()
    {
        return classPath;
    }

    /**
     * 获取运行类所在路径 例如运行类为：com.sinosoft.lis.bank.WagePayReadFromFileBL.class
     * 则调用该方法获取路径为：D:/jboss-eap-4.3/jboss-as/server/default/./deploy/ui.war/WEB-INF/classes/com/sinosoft/lis/bank
     * 此方法只支持class，不支持ui
     */
    public String getRuntimePath()
    {
        String runtimePath = "";
        String packagePath = "";

        Exception ex = new RuntimeException();
        try
        {
            StackTraceElement e2 = ex.getStackTrace()[1];
            packagePath = e2.toString();
            System.out.println("packagePath=" + packagePath);
            packagePath = packagePath.substring(0, packagePath.lastIndexOf("("));
            packagePath = packagePath.substring(0, packagePath.lastIndexOf("."));
            // 处理java/src下的无包文件
            if (packagePath.indexOf(".") == -1)
            {
                return ServerPath.getInstance().getClassPath();
            }
            packagePath = packagePath.substring(0, packagePath.lastIndexOf("."));
            packagePath = packagePath.replace(".", "/");
        } catch (IndexOutOfBoundsException e)
        {
            e.printStackTrace();
        } catch (NullPointerException e)
        {
            e.printStackTrace();
        }
        runtimePath = ServerPath.getInstance().getClassPath() + "/" + packagePath;
        System.out.println("runtimePath=" + runtimePath);
        return runtimePath;
    }
}